﻿using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;

namespace LeisureNcre.Helper
{
    public class DesHelper
    {
        private static string Key = "!1abcd2$";
        /// <summary>
        /// DES加密，对接其他语言使用同一规则用
        /// </summary>
        /// <param name="pToEncrypt"></param>
        /// <param name="key"></param>
        /// <param name="IV"></param>
        /// <returns></returns>
        public static string EncryptString(string pToEncrypt)
        {
            string encryptKeyall = Convert.ToString(Key);    //定义密钥  
            if (encryptKeyall.Length < 8)
            {
                for (; ; )
                {
                    if (encryptKeyall.Length < 8)
                        encryptKeyall += encryptKeyall;
                    else
                        break;
                }
            }
            string encryptKey = encryptKeyall.Substring(0, 8);
            //实例化加/解密类对象   
            DESCryptoServiceProvider descsp = new DESCryptoServiceProvider();
            descsp.Mode = CipherMode.CBC;
            descsp.Padding = PaddingMode.PKCS7;
            //定义字节数组，用来存储密钥    
            byte[] key = Encoding.UTF8.GetBytes(encryptKey);
            //定义字节数组，用来存储要加密的字符串  
            byte[] data = Encoding.UTF8.GetBytes(pToEncrypt);
            //实例化内存流对象   
            MemoryStream MStream = new MemoryStream();
            //使用内存流实例化加密流对象   
            CryptoStream CStream = new CryptoStream(MStream, descsp.CreateEncryptor(key, key), CryptoStreamMode.Write);
            //向加密流中写入数据      
            CStream.Write(data, 0, data.Length);
            //释放加密流      
            CStream.FlushFinalBlock();
            //返回加密后的字符串 
            return Convert.ToBase64String(MStream.ToArray());
        }
        /// <summary>
        /// DES解密
        /// </summary>
        /// <param name="decryptString"></param>
        /// <returns></returns>
        public static string DesDecrypt(string decryptString)
        {
            byte[] keyBytes = Encoding.UTF8.GetBytes(Key.Substring(0, 8));
            byte[] keyIV = keyBytes;
            byte[] inputByteArray = Convert.FromBase64String(decryptString);
            DESCryptoServiceProvider provider = new DESCryptoServiceProvider();
            MemoryStream mStream = new MemoryStream();
            CryptoStream cStream = new CryptoStream(mStream, provider.CreateDecryptor(keyBytes, keyIV), CryptoStreamMode.Write);
            cStream.Write(inputByteArray, 0, inputByteArray.Length);
            cStream.FlushFinalBlock();
            return Encoding.UTF8.GetString(mStream.ToArray());
        }
    }
}
